﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing.Imaging;
using Microsoft.Win32;
using System.Drawing.Drawing2D;
using System.Diagnostics;
using System.Reflection;
using LogLib;

namespace PixelDetectSDKInterface
{
    public class ComFun
    { 
        public static bool IsProcessExist(string strProcessName)
        {
            Process[] prc = Process.GetProcesses();
            foreach (Process pr in prc) //遍历整个进程
            {
                if (pr.ProcessName.Contains(strProcessName)) //如果进程存在
                {
                    return true;
                }
            }
            return false;
        }

        public static void ShutDown()
        {
            Process p = new Process();
            p.StartInfo.FileName = "shutdown.exe";
            p.StartInfo.Arguments = "-s -t 0";
            p.Start();
        }

        public static void ShutDownQuickly()
        {
            Process p = new Process();
            p.StartInfo.FileName = "shutdown.exe";
            p.StartInfo.Arguments = "-s -f -t 0";
            p.Start();
        }

        public static void KillProcess(string processName)
        {
            Process[] p = Process.GetProcessesByName(processName);
            for (int i = 0; i < p.Length; i++)
            {
                p[i].CloseMainWindow();
                p[i].Kill();
            }             
        }

        public static void Reboot()
        {
            Process p = new Process();
            p.StartInfo.FileName = "shutdown.exe";
            p.StartInfo.Arguments = "-r -t 0";
            p.Start();
        }

        public static byte[] ReadByteArray(string strFilePath)
        {
            using (FileStream stream = new FileInfo(strFilePath).OpenRead())
            {
                byte[] buffer = new Byte[stream.Length];
                stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
                stream.Close();
                return buffer;
            }
        }

        public static byte[] Bitmap2ByteArray(Bitmap img)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                img.Save(stream, ImageFormat.Jpeg);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
                return data;
            }
        }

        public static byte[] Bitmap2ByteArray_BMP(Bitmap img)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                img.Save(stream, ImageFormat.Bmp);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
                return data;
            }
        }

        public static Object Bitmap2Object(Bitmap img)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                img.Save(stream, ImageFormat.Jpeg);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
                return data;
            }
        }

        /// <summary>
        /// Resize图片
        /// </summary>
        /// <param name="bmp">原始Bitmap</param>
        /// <param name="newW">新的宽度</param>
        /// <param name="newH">新的高度</param>
        /// <param name="Mode">保留着，暂时未用</param>
        /// <returns>处理以后的图片</returns>
        public static Bitmap ResizeImage(Bitmap bmp, int newW, int newH, int Mode)
        {
            if (bmp == null)
            {
                return null;
            }
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                using (Graphics g = Graphics.FromImage(b))
                {
                    // 插值算法的质量
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                }    
                return b;
            }
            catch(Exception ex)
            {
                Log.WriteException(ex.ToString());
                return null;
            }
        }

  
        /// <summary>  
        /// 剪裁 -- 用GDI+   
        /// </summary>  
        /// <param name="b">原始Bitmap</param>       
        /// <param name="recArea">剪裁区域</param>
        /// <returns>剪裁后的Bitmap</returns>  
        public static Bitmap Cut(Bitmap b, Rectangle recArea)
        {
            if (b == null)
            {
                return null;
            }
            int w = b.Width;
            int h = b.Height;
            if (recArea.X >= w || recArea.Y >= h)
            {
                return null;
            }
            if (recArea.X + recArea.Width > w)
            {
                recArea.Width = w - recArea.X;
            }
            if (recArea.Y + recArea.Height > h)
            {
                recArea.Height = h - recArea.Y;
            }
            try
            {
                Bitmap bmpOut = new Bitmap(recArea.Width, recArea.Height, PixelFormat.Format24bppRgb);
                using (Graphics g = Graphics.FromImage(bmpOut))
                {
                    g.DrawImage(b, new Rectangle(0, 0, recArea.Width, recArea.Height), new Rectangle(recArea.X, recArea.Y, recArea.Width, recArea.Height), GraphicsUnit.Pixel);
                }                  
                return bmpOut;
            }
            catch(Exception ex)
            {
                Log.WriteException(ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 将Bmp转换为JPEG
        /// </summary>
        /// <param name="strSrc">Bmp文件路径</param>
        /// <param name="strDst">JPEG保存路径</param>
        /// <returns></returns>
        public static bool BmpToJpeg(string strSrc, string strDst)
        {
            if (!File.Exists(strSrc))
            {
                return false;
            }
            bool bRet = false;
            Bitmap bitmap = new Bitmap(strSrc);
            Bitmap newImg = new Bitmap(bitmap.Width, bitmap.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            try
            {              
                newImg.SetResolution(300.0f, 300.0f);
                using (Graphics graphic = Graphics.FromImage(newImg))
                {
                    //设置高质量查值法
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    //设置高质量，低速度呈现平滑程度
                    graphic.SmoothingMode = SmoothingMode.HighQuality;
                    //清空画布并以透明背景色填充
                    graphic.Clear(System.Drawing.Color.Transparent);
                    graphic.DrawImage(bitmap,
                        new Rectangle(0, 0, newImg.Width, newImg.Height),
                        new Rectangle(0, 0, newImg.Width, newImg.Height),
                        System.Drawing.GraphicsUnit.Pixel);
                }
                ImageCodecInfo[] vImageCodecInfos = ImageCodecInfo.GetImageEncoders();
                foreach (ImageCodecInfo vImageCodecInfo in vImageCodecInfos)
                {
                    if (vImageCodecInfo.FormatDescription.ToLower() == "jpeg")
                    {
                        EncoderParameters vEncoderParameters = new EncoderParameters(1);
                        vEncoderParameters.Param[0] = new EncoderParameter(
                            System.Drawing.Imaging.Encoder.Quality, 95L);
                        newImg.Save(strDst, vImageCodecInfo, vEncoderParameters);
                        //ResizeImage(strDst);
                        break;
                    }
                }                             
                bRet = true;
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
            }
            finally
            {
                if (newImg != null)
                {
                    newImg.Dispose();
                    newImg = null;
                }
                if (bitmap != null)
                {
                    bitmap.Dispose();
                    bitmap = null;
                }              
            }
            return bRet;
        }

        public static void ResizeImage(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Append);
            byte[] b = { 0x00 };
            while (fs.Length < 22 * 1024)
            {
                fs.Write(b, 0, b.Length);
            }
            fs.Flush();
            fs.Close();
        }

        public static string OSName()
        {
            RegistryKey rk;
            rk = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion");
            string OSname = rk.GetValue("ProductName").ToString();//产品名称（系统名称）
            string buildNumber = rk.GetValue("CurrentBuildNumber").ToString();//系统版本号
            rk.Close();
            return OSname;
        }
        public static bool IsInDebugMode(string FileName)
        {
            var assembly = System.Reflection.Assembly.LoadFile(FileName);
            var attributes = assembly.GetCustomAttributes(typeof(System.Diagnostics.DebuggableAttribute), false);
            if (attributes.Length > 0)
            {
                var debuggable = attributes[0] as System.Diagnostics.DebuggableAttribute;
                if (debuggable != null)
                    return (debuggable.DebuggingFlags & System.Diagnostics.DebuggableAttribute.DebuggingModes.Default) == System.Diagnostics.DebuggableAttribute.DebuggingModes.Default;
                else
                    return false;
            }
            else
                return false;
        }     
    }
}
